import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/user_info_entity.dart';
import 'package:taonile/provider/userinfo_provider.dart';
import 'package:taonile/utils/common_utils.dart';
import 'package:taonile/utils/user_utils.dart';
import 'package:taonile/views/dialog_manager.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../http/api.dart';
import '../routers/routers.dart';

class HomeMine extends StatefulWidget {
  const HomeMine({Key? key}) : super(key: key);

  @override
  State<HomeMine> createState() => _HomeMineState();

  ///
  /// 请求个人中心接口
  ///
  getUserInfo(Function onSucces) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString("token");
    if (token != null) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }
}

class _HomeMineState extends State<HomeMine> {
  ///
  /// 资产区item
  ///
  Widget getAssetItem(String icon, String name, String count, Function() onTap) {
    return Container(
      width: double.infinity,
      height: 108.w,
      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 24.w),
      margin: EdgeInsets.fromLTRB(0.w, 0.w, 0.w, 0.w),
      // decoration: BoxDecoration(
      //   border: Border(bottom: BorderSide(width: 3.w, color: Config.colorDivider)),
      // ),
      child: InkWell(
        onTap: onTap,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Image.asset(
                  icon,
                  width: 52.w,
                  height: 52.w,
                  fit: BoxFit.fill,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 30.w),
                ),
                Text(
                  name,
                  style: TextStyle(fontSize: 26.sp, height: 1.5, color: Config.colorText1),
                ),
              ],
            ),
            Text(
              count,
              style: TextStyle(fontSize: 26.sp, height: 1.5, color: Config.colorText1),
            ),
          ],
        ),
      ),
    );
  }

  ///
  /// 金刚区的Item
  ///
  Widget getJingangItem(String icon, String name, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            icon,
            width: 48.w,
            height: 48.w,
            errorBuilder: (ctx, err, stacktrace) => Image.asset(
              'assets/images/bg_default_400.png',
              width: 48.w,
              height: 48.w,
              fit: BoxFit.fill,
            ),
          ),
          Text(name, style: TextStyle(fontSize: 21.sp, height: 1.8, color: Config.colorText1)),
        ],
      ),
    );
  }

  Widget getLoginOutView() {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 0) {
      return const Padding(padding: EdgeInsets.all(0));
    } else {
      return Container(
        width: double.infinity,
        height: 98.w,
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
        margin: EdgeInsets.symmetric(vertical: 14.w, horizontal: 35.w),
        child: ElevatedButton(
          onPressed: () {
            DialogManager.showDefaultDialog(context, "确认退出登录吗", () {
              UserUtils.loginOut(context);
            });
          },
          style: ElevatedButton.styleFrom(
            primary: Config.colorMain,
            onPrimary: Config.colorBg,
            shadowColor: Config.colorBg,
            elevation: 0,
            // shape: const StadiumBorder(),
          ),
          child: const Text(
            "退出登录",
            style: TextStyle(color: Config.colorWhite),
          ),
        ),
      );
    }
  }

  ///
  /// 返回用户名的布局，登录与未登录分别返回不同的布局
  ///
  Widget showIsLogin(context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 1) {
      return Padding(
        padding: EdgeInsets.fromLTRB(25.w, 0.w, 25.w, 2.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              infoEntity.data.name,
              style: TextStyle(color: Config.colorWhite, fontSize: 36.sp),
            ),
            Padding(
              padding: EdgeInsets.all(8.w),
            ),
            Visibility(
              visible: (infoEntity.data.levelName.isNotEmpty ||
                  infoEntity.data.copartnerName.isNotEmpty),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Visibility(
                    visible: infoEntity.data.levelName.isNotEmpty,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular(20.w),
                        border: Border.all(color: Config.colorWhite, width: 2.w),
                      ),
                      padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 10.w),
                      margin: EdgeInsets.only(left: 0.w),
                      child: Text(
                        infoEntity.data.levelName,
                        // entity.code == 1 ? entity.data.info.level : '',
                        style: TextStyle(fontSize: 15.sp, color: Config.colorWhite),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: infoEntity.data.copartnerName.isNotEmpty,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular(20.w),
                        border: Border.all(color: Config.colorWhite, width: 2.w),
                      ),
                      padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 10.w),
                      margin: EdgeInsets.only(left: 15.w),
                      child: Text(
                        infoEntity.data.copartnerName,
                        // entity.code == 1 ? entity.data.info.level : '',
                        style: TextStyle(fontSize: 15.sp, color: Config.colorWhite),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    } else {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 25.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () {
                Routes.router
                    .navigateTo(context, Routes.login, transition: TransitionType.inFromRight);
              },
              child: Text(
                '点击登录',
                style: TextStyle(color: Config.colorWhite, fontSize: 38.sp),
              ),
            ),
          ],
        ),
      );
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.getUserInfo((UserInfoEntity infoEntity) {
      Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
    });
  }

  goToOrderIndex(int index) {
    Routes.navigateTo(context, Routes.orderIndex, params: {'currentIndex': index.toString()})
        .then((value) {
      widget.getUserInfo((UserInfoEntity infoEntity) {
        Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    return Scaffold(
      body: Container(
        color: Config.colorBg2,
        width: double.infinity,
        height: double.infinity,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Stack(
            children: [
              Image.asset(
                'assets/images/mine_top_bg.png',
                width: double.infinity,
                height: 430.w,
                fit: BoxFit.fill,
              ),
              Column(
                children: [
                  Container(
                    //头像区
                    height: 130.w,
                    margin: EdgeInsets.fromLTRB(40.w, 110.w, 0, 0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ClipOval(
                          child: InkWell(
                            onTap: () async {
                              if (await UserUtils.isLogin() == false) {
                                return;
                              }
                              Routes.navigateTo(context, Routes.mineInfo);
                            },
                            child: Container(
                              width: 130.w,
                              height: 130.w,
                              color: (Config.colorWhite),
                              padding: EdgeInsets.all(3.w),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(130),
                                child: CachedNetworkImage(
                                  imageUrl: infoEntity.code == 1
                                      ? CommonUtils.compressImageUrl(
                                          infoEntity.data.avatar, 200, 200)
                                      : '',
                                  fit: BoxFit.fill,
                                  width: double.infinity,
                                  height: double.infinity,
                                  errorWidget: (context, url, error) {
                                    return Image.asset(
                                      'assets/images/icon_default_head.jpg',
                                      width: double.infinity,
                                      height: double.infinity,
                                      fit: BoxFit.fill,
                                    );
                                  },
                                ),
                              ),
                            ),
                          ),
                        ),
                        showIsLogin(context),
                      ],
                    ),
                  ),

                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    margin: EdgeInsets.fromLTRB(40.w, 45.w, 40.w, 0),
                    padding: EdgeInsets.symmetric(vertical: 0.w),
                    child: Column(
                      children: [
                        getAssetItem('assets/images/icon_mine_usdt.png', "USDT",
                            infoEntity.code == 1 ? infoEntity.data.usdt : "0", () async {
                          if (await UserUtils.isLogin() == false) {
                            return;
                          }
                          Routes.navigateTo(context, Routes.assetGeneralDetail, params: {
                            'pageTitle': 'USDT',
                            'assetType': 'usdt',
                            'amount': infoEntity.data.usdt
                          });
                        }),
                        Divider(color: Config.colorDivider, height: 2.w, thickness: 2.w),
                        getAssetItem('assets/images/icon_mine_qdys.png', "QDYS",
                            infoEntity.code == 1 ? infoEntity.data.qdys : "0", () async {
                          if (await UserUtils.isLogin() == false) {
                            return;
                          }
                          Routes.navigateTo(context, Routes.assetGeneralDetail, params: {
                            'pageTitle': 'QDYS',
                            'assetType': 'qdys',
                            'amount': infoEntity.data.qdys
                          });
                        }),
                        Divider(color: Config.colorDivider, height: 2.w, thickness: 2.w),
                        getAssetItem('assets/images/icon_mine_allasset.png', "总资产包",
                            infoEntity.code == 1 ? infoEntity.data.totalAssets : "0", () async {
                          if (await UserUtils.isLogin() == false) {
                            return;
                          }
                          Routes.navigateTo(
                            context,
                            Routes.assetPackge,
                          );
                        }),
                      ],
                    ),
                  ),
                  Container(
                    //金刚区
                    width: double.infinity,
                    height: 195.w,
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 18.w),
                    margin: EdgeInsets.fromLTRB(40.w, 30.w, 40.w, 0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 20.w, horizontal: 6.w),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '我的订单',
                                style: TextStyle(fontSize: 25.sp),
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  InkWell(
                                    onTap: () async {
                                      if (await UserUtils.isLogin() == false) {
                                        return;
                                      }
                                      goToOrderIndex(0);
                                    },
                                    child: Text(
                                      '查看全部',
                                      style: TextStyle(fontSize: 23.sp, color: Config.colorText3),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 5.w),
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    size: 25.w,
                                    color: Config.colorText3,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 10.w),
                        ),
                        Stack(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                getJingangItem('assets/images/icon_mine_pay.png', "待付款", () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  goToOrderIndex(1);
                                }),
                                getJingangItem('assets/images/icon_mine_send.png', "待发货", () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  goToOrderIndex(2);
                                }),
                                getJingangItem('assets/images/icon_mine_receive.png', "待收货",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  goToOrderIndex(3);
                                }),
                                getJingangItem('assets/images/icon_mine_pay.png', "退款/售后",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.orderRefundList);
                                }),
                              ],
                            ),
                            Positioned(
                              right: 170.w,
                              child: Container(
                                height: 65.w,
                                width: 2.w,
                                decoration: const BoxDecoration(color: Color(0xFFF5F5F5)),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Container(
                      //中间列表区
                      width: double.infinity,
                      margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 40.w),
                      decoration: BoxDecoration(
                        color: Config.colorBg,
                        borderRadius: BorderRadius.circular(12.w),
                      ),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 20.w, horizontal: 25.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '更多功能',
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 0.w),
                          ),
                          SizedBox(
                            height: 360.w,
                            child: GridView.count(
                              // shrinkWrap: true,
                              padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 30.w),
                              mainAxisSpacing: 0.w,
                              physics: const NeverScrollableScrollPhysics(),
                              crossAxisSpacing: 40.w,
                              childAspectRatio: 1.6,
                              crossAxisCount: 3,
                              children: [
                                getJingangItem('assets/images/icon_mine_collect.png', "我的收藏",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineCollect);
                                }),
                                getJingangItem('assets/images/icon_mine_mycard.png', "我的名片",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineShareCard);
                                }),
                                getJingangItem('assets/images/icon_mine_team.png', "我的团队",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineTeam,
                                      params: {'userId': infoEntity.data.id, 'isMe': "1"});
                                }),
                                getJingangItem('assets/images/icon_mine_address.png', "收货地址",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineAddressManager);
                                }),
                                getJingangItem('assets/images/icon_mine_bankcard.png', "银行卡管理",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineBankcardManager);
                                }),
                                getJingangItem('assets/images/icon_mine_shop_into.png', "商家入驻",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.myStoreToJoinBefore);
                                }),
                                getJingangItem('assets/images/icon_mine_stock.png', "我的股票",
                                    () async {
                                  if (await UserUtils.isLogin() == false) {
                                    return;
                                  }
                                  Routes.navigateTo(context, Routes.mineStock);
                                }),

                                getJingangItem('assets/images/icon_mine_setting.png', "设置", () {
                                  Routes.navigateTo(context, Routes.mineSetting);
                                }),
                              ],
                            ),
                          ),
                        ],
                      )),
                  // getLoginOutView(),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
